package com.it.mydream.Controller;

import com.it.mydream.Bean.Rank;
import com.it.mydream.Bean.User;
import com.it.mydream.Service.imp.LoginServiceImp;
import com.it.mydream.Service.imp.RankServiceImp;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.List;

@Controller
public class SnakeController {
    @Autowired
    private RankServiceImp rkService;
    @Autowired
    private LoginServiceImp loginService;

    @RequestMapping("goSnake")
    public String goSnake(HttpServletRequest request){
        HttpSession session = request.getSession();
        ServletContext application = request.getServletContext();
        User user = (User) session.getAttribute("user");
        user.setUser_status("20006");
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setUser_status_time(sdf.format(System.currentTimeMillis()));
        loginService.updateUserStatus(user);

        List<User> userlist = loginService.getUserList();
        application.setAttribute("userlist",userlist);

        List<Rank> ranks = rkService.selectRanks("30001");
        request.setAttribute("ranks",ranks);
        return "game/snake";
    }

    @RequestMapping("uploadRank")
    @ResponseBody
    public void uploadRank(HttpServletRequest request){
        String type = request.getParameter("type");
        String score = request.getParameter("score");

        HttpSession session = request.getSession();
        ServletContext application = request.getServletContext();
        User user = (User) session.getAttribute("user");

        Rank rank_t = new Rank();
        rank_t.setUser(user);
        rank_t.setType(type);
        Rank rank = rkService.selectRank(rank_t);
        if(rank == null){
            rank_t.setScore(score);
            rank_t.setCount("1");
            rkService.insertRank(rank_t);
        }else{
            String o_score = rank.getScore();
            String o_count = rank.getCount();
            if(Integer.parseInt(o_score)<Integer.parseInt(score)){
                rank.setScore(score);
            }
            rank.setCount(String.valueOf(Integer.parseInt(o_count)+1));
            rank.setType(type);
            rkService.updateRank(rank);
        }
    }

}
